{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第1关：感知机 - 西瓜好坏自动识别\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#encoding=utf8\n",
    "import numpy as np\n",
    "#构建感知机算法\n",
    "class Perceptron(object):\n",
    "    def __init__(self, learning_rate = 0.01, max_iter = 1000):\n",
    "        self.lr = learning_rate\n",
    "        self.max_iter = max_iter\n",
    "    def fit(self, data, label):\n",
    "        '''\n",
    "        input:data(ndarray):训练数据特征\n",
    "              label(ndarray):训练数据标签\n",
    "        output:w(ndarray):训练好的权重\n",
    "               b(ndarry):训练好的偏置\n",
    "        '''\n",
    "        #编写感知机训练方法，w为权重，b为偏置\n",
    "        self.w = np.array([1.]*data.shape[1])\n",
    "        self.b = np.array([1.])\n",
    "        #********* Begin *********#\n",
    "        for i in range(0, self.max_iter):\n",
    "            con = label * np.dot(data, self.w)  # con.shape=(样本数量，)\n",
    "            x1 = data[np.where(con<0)]\n",
    "            y1 = label[np.where(con<0)]\n",
    "            self.w += self.lr *  np.sum((x1 * y1.reshape(len(y1), -1)).T, axis=1)\n",
    "            self.b += self.lr * np.sum(y1)\n",
    "        #********* End *********#\n",
    "    def predict(self, data):\n",
    "        '''\n",
    "        input:data(ndarray):测试数据特征\n",
    "        output:predict(ndarray):预测标签\n",
    "        '''\n",
    "        #********* Begin *********#\n",
    "        predict = np.where(np.dot(data, self.w) + self.b > 0, 1, -1)\n",
    "        #********* End *********#\n",
    "        return predict\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Perceptron\n",
    "在 sklearn 中，使用 Perceptron 方法实现感知机算法，Perceptron 的构造函数中有两个常用的参数可以设置：\n",
    "\n",
    "- eta0：学习率大小，默认为 1.0 ；\n",
    "- max_iter：最大训练轮数。\n",
    "\n",
    "和 sklearn 中其他分类器一样， Perceptron 类中的 fit 函数用于训练模型， fit 函数有两个向量输入：\n",
    "\n",
    "- X ：大小为 [样本数量,特征数量] 的 ndarray，存放训练样本；\n",
    "- Y ：值为整型，大小为 [样本数量] 的 ndarray，存放训练样本的分类标签。\n",
    " \n",
    "Perceptron 类中的 predict 函数用于预测，返回预测标签， predict 函数有一个向量输入：\n",
    "\n",
    "- X ：大小为[样本数量,特征数量]的 ndarray ，存放预测样本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#encoding=utf8\n",
    "import os\n",
    "\n",
    "if os.path.exists('./step2/result.csv'):\n",
    "    os.remove('./step2/result.csv')\n",
    "\n",
    "#********* Begin *********#\n",
    "import pandas as pd\n",
    "#获取训练数据\n",
    "train_data = pd.read_csv('./step2/train_data.csv')\n",
    "#获取训练标签\n",
    "train_label = pd.read_csv('./step2/train_label.csv')\n",
    "train_label = train_label['target']\n",
    "#获取测试数据\n",
    "test_data = pd.read_csv('./step2/test_data.csv')\n",
    "\n",
    "from sklearn.linear_model import Perceptron\n",
    "clf = Perceptron(eta0=0.01, max_iter=1000)\n",
    "clf.fit(train_data, train_label)\n",
    "result = clf.predict(test_data)\n",
    "\n",
    "res = pd.DataFrame(result, columns=['result'])\n",
    "res.to_csv('./step2/result.csv')\n",
    "#********* End *********#\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tf38",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
